package com.easybuy.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

// 全局日志过滤器:记录所有请求的详细信息和响应状态，用于审计和调试。
// 该过滤器在 Pre 阶段记录请求方法、路径和客户端 IP，在 Post 阶段记录请求处理时长和响应状态码，帮助开发人员了解请求处理情况和系统性能。
@Component
@Order(-200)
@Slf4j
public class GlobalLoggingFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // Pre阶段：记录请求信息
        ServerHttpRequest request = exchange.getRequest();
        long startTime = System.currentTimeMillis();
        log.info("Request: {} {} from {}",
                request.getMethod(),
                request.getURI(),
                request.getRemoteAddress());

        // Post阶段：记录响应信息
        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {

                    ServerHttpResponse response = exchange.getResponse();
                    long duration = System.currentTimeMillis() - startTime;
                    log.info("Response: {} {} completed in {}ms",
                            request.getMethod(),
                            request.getURI(),
                            duration);
                    log.info("Response status: {}", response.getStatusCode());
                }));
    }

    @Override
    public int getOrder() {

        return -200;
    }
}